package com.sjb.singleequipment.service.impl;

import cn.hutool.core.util.StrUtil;
import com.sjb.singleequipment.SessionManager;
import com.sjb.singleequipment.model.User;
import com.sjb.singleequipment.service.UserService;
import com.sjb.singleequipment.util.NetUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.sjb.singleequipment.RedisKeyConstant.USER_LOGIN_STATE;

/**
 * @Author:sjb
 * @CreateTime:2024-08-18
 * @Description: 用户接口实现类
 * @Version：1.0
 */
@Component
public class UserServiceImpl implements UserService {

    @Resource
    private SessionManager sessionManager;

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser ==  null || currentUser.getId() == null){
            throw new RuntimeException("未登录");
        }
        // 校验是否已在其他客户端登录
        String ipAddress = NetUtils.getIpAddress(request);
        String oldSessionId = sessionManager.checkOthLogin(currentUser.getId(), ipAddress, request);
        if (StrUtil.isNotBlank(oldSessionId)){
            request.getSession().removeAttribute(USER_LOGIN_STATE);
            throw new RuntimeException("已在其他设备登录，请重新登录");
        }
        // 从数据库查询
        long userId = currentUser.getId();
        currentUser = this.getUserById(String.valueOf(userId));
        if (currentUser ==  null){
            throw new RuntimeException("当前未登录");
        }
        return currentUser;
    }

    public User getUserById(String userId) {
        // todo 从数据库根据userId查询用户信息
        return null;
    }
}
